package controller

import (
	"errors"
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"math"
	"net/http"
)

type CartHandler struct {
}

func (*CartHandler) GetGoodsCount(ctx *gin.Context) {
	res := utils.NewResponse()
	id, exits := ctx.Get("id")
	if !exits {
		res.SetRes(1, "id不存在", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	userId := id.(uint)
	cart := models.Cart{}
	count, err := cart.GetCartCountByUserId(int(userId))
	if err != nil {
		res.SetRes(1, "error", err)
		ctx.JSON(http.StatusBadGateway, res)
		return
	}

	data := make(map[string]any)
	data["cartTotal"] = map[string]any{
		"goodsCount": count,
	}
	res.SetRes(0, "success", data)
	ctx.JSON(http.StatusOK, res)
}

func (*CartHandler) Index(ctx *gin.Context) {
	res := utils.NewResponse()
	id, exits := ctx.Get("id")
	if !exits {
		res.SetRes(1, "id不存在", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	userId := id.(uint)
	cart := models.Cart{}
	cart.UserId = userId
	var isFast int8 = 0
	cartList, err := cart.GetCartByType(isFast)
	if err != nil {
		res.SetRes(1, "服务器发生错误", err)
		ctx.JSON(http.StatusBadGateway, res)
		return
	}

	var goodsCount = 0
	var goodsAmount float64 = 0
	var checkedGoodsCount = 0
	var checkedGoodsAmount float64 = 0
	var numberChange = 0

	for _, v := range cartList {
		product := models.Product{}
		product.ID = v.ProductId
		err := product.GetProductById()
		// 商品被删了
		if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
			cart.ProductId = product.ID
			cart.UserId = uint(userId)
			cart.IsDelete = 0
			err = cart.Update(map[string]any{
				"is_delete": 1,
			})
			if err != nil {
				res.SetRes(1, "更新失败", err)
				ctx.JSON(http.StatusBadGateway, res)
				return
			}
		} else {
			var retailPrice = product.RetailPrice
			var productNum = uint8(product.GoodsNumber)

			if productNum <= 0 || product.IsOnSale == 0 {
				cart.ProductId = v.ProductId
				cart.UserId = uint(userId)
				cart.Checked = 1
				cart.IsDelete = 0
				err = cart.Update(map[string]any{
					"checked": 0,
				})
				if err != nil {
					res.SetRes(1, "更新失败", err)
					ctx.JSON(http.StatusOK, res)
					return
				}
				v.Number = 0
			} else if productNum < v.Number {
				v.Number = productNum
				numberChange = 1
			} else if v.Number == 0 {
				v.Number = 1
				numberChange = 1
			}

			goodsCount += int(v.Number) // 小转大
			goodsAmount += float64(v.Number) * retailPrice
			v.RetailPrice = retailPrice

			if !(v.Checked == 1 && productNum > 0) {
				checkedGoodsCount += int(v.Number)
				checkedGoodsAmount += float64(v.Number) * retailPrice
			}

			goods := models.Goods{}

			goods.ID = v.GoodsId
			err = goods.GetDetail()
			if err != nil {
				res.SetRes(1, "查找失败", err)
				ctx.JSON(http.StatusBadGateway, res)
				return
			}

			v.ListPicUrl = goods.ListPicUrl
			v.GoodsWeight = float32(v.Number) * v.GoodsWeight

			cart.ProductId = v.ProductId
			cart.UserId = uint(userId)
			cart.IsDelete = 0
			err = cart.Update(map[string]any{
				"number":    v.Number,
				"add_price": retailPrice,
			})
			if err != nil {
				res.SetRes(1, "更新失败", err)
				ctx.JSON(http.StatusBadGateway, res)
				return
			}
		}
	}

	var cAmount = math.Trunc(checkedGoodsAmount*1e2+0.5) * 1e-2

	data := map[string]any{
		"cartList": cartList,
		"cartTotal": map[string]any{
			"goodsCount":         goodsCount,
			"goodsAmount":        goodsAmount,
			"checkedGoodsAmount": cAmount,
			"checkedGoodsCount":  checkedGoodsCount,
			"user_id":            userId,
			"numberChange":       numberChange,
		},
	}

	res.SetRes(0, "success", data)
	ctx.JSON(http.StatusOK, res)

}
